#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "framework/hashtable/uthash.h"

struct hashTable
{
    int key;
    int val;
    UT_hash_handle hh;
};

struct hashTable *my_ht;
static struct hashTable *hash_find(int ikey);
static void hash_insert(int ikey, int ival);
int longestConsecutive(int *nums, int numsSize);

static struct hashTable *hash_find(int ikey)
{
    struct hashTable *tmp;
    HASH_FIND_INT(my_ht, &ikey, tmp);
    return tmp;
}

static void hash_insert(int ikey, int ival)
{
    struct hashTable *it = hash_find(ikey);
    if (it == NULL)
    {
        struct hashTable *tmp = malloc(sizeof(struct hashTable));
        tmp->key = ikey;
        tmp->val = ival;
        HASH_ADD_INT(my_ht, key, tmp);
    }
    else
    {
        it->val = ival;
    }

    printf("insert str: %d, raw str: %d\n", ikey, ival);
}

int longestConsecutive(int *nums, int numsSize)
{
    if (0 == numsSize)
    {
        return 0;
    }

    my_ht = NULL;

    for (int i = 0; i < numsSize; i++)
    {
        int num = *(nums + i);
        hash_insert(num, num);
    }

    int max_counter = 0;
    struct hashTable *el, *tmp;
    HASH_ITER(hh, my_ht, el, tmp)
    {
        printf("el->key: %d\n", el->key);
        int num = el->key;
        if (NULL == hash_find(num - 1))
        {
            printf("No head for: %d, so it is HEAD!\n", num);
            int counter = 1;
            while (hash_find(num + 1) != NULL)
            {
                counter++;
                printf("find the next data: %d, the counter is: %d\n", num + 1, counter);

                num++;
            }

            max_counter = max_counter > counter ? max_counter : counter;
        }
        else
        {
            printf("find the head for %d, so just skip!\n", num);
        }
    }

    return max_counter;
}

void main(void)
{
    // int nums[] = {100, 4, 200, 1, 3, 2};
    // int nums[] = {0, 3, 7, 2, 5, 8, 4, 6, 0, 1};
    int nums[] = {1, 2, 0, 1};
    // int nums[] = {0};
    int num_count = sizeof(nums) / sizeof(int);
    printf("num_count: %d\n", num_count);
    int max_counter = longestConsecutive(nums, num_count);

    printf("max_count: %d\n", max_counter);
}